<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import {
    List,
    ListItem,
    ListItemMeta,
    Avatar,
    Space,
    Spin,
    Tabs,
    TabPane,
    Divider,
    TypographyTitle,
    TypographyParagraph,
  } from '@arco-design/web-vue';
  import { appSpColumnInfo, changeSubscribe } from '/@/api/column';
  import type { ArticleRecord } from '/@/api/model/articleModel';
  import type { SpColumnRecord } from '/@/api/model/columnModel';
  import { queryArticleList } from '/@/api/recommend';
  import { useGlobalScroll } from '/@/hooks/useScroll';
  import { useUserStore } from '/@/store/modules/user';
  const isLoading = ref(false);
  const subscribeLoding = ref(false);

  const route = useRoute();
  const sp_column_id = ref<number>();
  const spColumnInfo = ref<SpColumnRecord>();
  const userStore = useUserStore();
  const userInfo = computed(() => userStore.getUserInfo);
  watch(
    () => route.params.id,
    (id) => {
      sp_column_id.value = parseInt(Array.isArray(id) ? id[0] : id, 10) ?? 0;
    },
    { immediate: true },
  );

  async function updateSpColumnInfo([sp_column_id]) {
    if (sp_column_id) {
      isLoading.value = true;

      if (userInfo.value && userInfo.value.id) {
        // 检查是否定义了 userInfo.value 和 userInfo.value.id
        spColumnInfo.value = await appSpColumnInfo({
          id: sp_column_id,
          user_id: userInfo.value.id,
        });
      } else {
        spColumnInfo.value = await appSpColumnInfo({ id: sp_column_id, user_id: null }); // 如果未定义用户 ID，则不传递 user_id 参数
      }

      isLoading.value = false;
    }
  }

  watch([sp_column_id], updateSpColumnInfo, { immediate: true });

  // 距离底部 100 px 时触发
  const { arrivedState } = useGlobalScroll({ offset: { bottom: 100 } });

  // 文章列表
  const articleList = ref<ArticleRecord[]>([]);
  const page = ref(1);
  const articleListLoading = ref(false);
  watch(
    [page],
    async ([page]) => {
      if (articleListLoading.value) return;
      articleListLoading.value = true;

      const result = await queryArticleList({
        sp_column_id: sp_column_id.value,
        column_id: '',
        page,
        size: 20,
      });
      articleList.value.push(...result.list);

      articleListLoading.value = false;
    },
    { immediate: true },
  );
  watch(
    () => arrivedState.bottom,
    (isReachBottom) => {
      if (isReachBottom) {
        if (articleListLoading.value) return;
        page.value++;
      }
    },
  );

  const getSubscribe = async () => {
    subscribeLoding.value = true;

    await changeSubscribe(spColumnInfo.value?.id, spColumnInfo.value?.is_subscribe);

    await updateSpColumnInfo([sp_column_id.value]);

    subscribeLoding.value = false;
  };
</script>
<template>
  <div class="w-full mt-[20px] px-[160px]">
    <a-card :bordered="false" class="p-[5px]">
      <div class="text-[25px] font-black text-[#000]">{{ spColumnInfo?.name }}</div>
      <a-row class="mt-[5px]" :gutter="10">
        <a-col :span="5">
          <img :src="spColumnInfo?.cover" class="details-img" width="200" height="125" />
        </a-col>
        <a-col :span="15">
          <a-row>
            <a-col :span="1">
              <a-avatar class="mr-[8px]" :size="24" :image-url="spColumnInfo?.user_icon" />
            </a-col>
            <al-col :span="23" class="ml-[10px] mt-[3px] font-black text-[#666]">{{
              spColumnInfo?.user_name
            }}</al-col>
          </a-row>
          <a-typography-paragraph
            class="mt-[10px] h-[45px] font-black text-[#777]"
            :ellipsis="{
              rows: 2,
              showTooltip: true,
            }"
          >
            {{ spColumnInfo?.desc }}
          </a-typography-paragraph>
          <a-row>
            <a-col :span="1" v-for="(item, index) in spColumnInfo?.top5" :key="index">
              <a-avatar
                class="filter-shadow ml-[-5px] bg-transparent"
                :size="22"
                :image-url="item?.user_icon"
              />
            </a-col>
            <a-col :span="19" class="mt-[3px]">
              <span class="font-[800] text-[#999] ml-[2px]"
                >等{{ spColumnInfo?.spUserCount }}人订阅</span
              >
              <span class="font-[800] text-[#999] ml-[10px]"
                >共{{ spColumnInfo?.article_num }}篇文章</span
              >
              <span class="font-[800] text-[#999] ml-[10px]"
                >创建于{{ spColumnInfo?.createTime }}</span
              >
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="4" class="text-center">
          <a-button
            v-if="spColumnInfo?.is_subscribe === false"
            type="primary"
            class="mt-[90px]"
            @click="getSubscribe"
            :loading="subscribeLoding"
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>订阅专栏</template>
          </a-button>
          <a-button
            v-if="spColumnInfo?.is_subscribe === true"
            class="mt-[90px]"
            @click="getSubscribe"
            :loading="subscribeLoding"
          >
            <template #icon>
              <icon-check />
            </template>
            <template #default>已订阅</template>
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <div class="bg-white rounded-[3px] mt-[15px]">
      <Tabs default-active-key="1">
        <template #extra>
          <a-dropdown>
            <a-button type="text">默认排序 <icon-right /></a-button>
            <template #content>
              <a-doption>Option 1</a-doption>
              <a-doption disabled>Option 2</a-doption>
              <a-doption :value="{ value: 'Option3' }">Option 3</a-doption>
            </template>
          </a-dropdown>
        </template>
        <TabPane key="1" title="收录文章" />
      </Tabs>
      <List :bordered="false" size="small">
        <template #scroll-loading v-if="articleListLoading">
          <Spin :size="32" :loading="true" />
        </template>
        <template v-for="item in articleList" :key="item.id">
          <a class="block" :href="'/post/' + item.id" target="_blank">
            <ListItem class="list-hover">
              <ListItemMeta class="border-b border-gray-100">
                <template #description>
                  <div class="flex flex-col px-[12px] pt-[8px]">
                    <div class="flex-none">
                      <Avatar class="mr-[8px]" :size="24">
                        <img alt="avatar" :src="item.user_icon" />
                      </Avatar>
                      <span class="text-black">{{ item.user_name }}</span>
                      <Divider direction="vertical" />
                      <span class="text-[12px] text-[#8A919F]">{{
                        $timeAgo(item.createTime)
                      }}</span>
                      <Divider direction="vertical" />
                      <span>
                        <a-tag
                          color="gray"
                          size="small"
                          class="text-[12px] ml-[5px]"
                          v-for="(tag, index) in item.tag.split(',')"
                          :key="index"
                        >
                          {{ tag }}
                        </a-tag>
                      </span>
                    </div>
                    <div class="flex justify-between flex-1">
                      <div class="mt-[-8px]">
                        <TypographyTitle :heading="6" ellipsis bold>
                          {{ item.title }}
                        </TypographyTitle>
                        <TypographyParagraph
                          class="text-[#8A919F]"
                          spacing="close"
                          :ellipsis="{
                            rows: 2,
                            showTooltip: false,
                            css: false,
                          }"
                        >
                          {{ item.brief }}
                        </TypographyParagraph>
                        <!-- <div class="text-gray-500 text-ellipsis">{{ item.brief }}</div> -->
                      </div>
                      <div class="w-[188px] ml-[24px] flex-none" v-if="item.cover">
                        <div class="h-[130px] rounded-[2px] overflow-hidden">
                          <img :src="item.cover" />
                        </div>
                      </div>
                    </div>
                    <div class="flex flex-none justify-between">
                      <Space class="flex-start text-[#8A919F]">
                        <span><IconEye /> {{ item.read }}</span>
                        <span><IconMessage /> {{ item.recommend }}</span>
                      </Space>
                    </div>
                  </div>
                </template>
              </ListItemMeta>
            </ListItem>
          </a>
        </template>
      </List>
    </div>
  </div>
</template>
<style scoped>
  .details-img {
    width: 200px;
    height: 120px;
  }
</style>
